import React from 'react';
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheButton from "@/components/TheButton";
import TheSwitch from "@/components/TheSwitch";
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import { apiBannerPage, apiBannerEdit, apiBannerDel } from '@/request/petCircleUtil/banner'
import TheImage from '@/components/TheImage'
import store from "@/store/store"
import _ from 'lodash';

import { Space, Input, Switch, InputNumber, message, Form } from "antd";

const { TextArea } = Input;

class Resource extends React.Component {
    sortRef = React.createRef();
    queryFormRef = React.createRef();
    state = {
        changeFlag: false,
        columns: [
            {
                title: "资源位类型",
                dataIndex: "bannerType",
                key: "bannerType",
                render: (_, render) => {
                    const arr = ["", "banner区", "内容首位资源区"]
                    return (
                        <div>{arr[render.bannerType]}</div>
                    )
                }
            },
            {
                title: "资源位名称",
                dataIndex: "bannerName",
                key: "bannerName",
            },
            {
                title: "排序",
                dataIndex: "sort",
                key: "sort",
                sorter: true,
                render: (_, render) => {
                    return (
                        <InputNumber value={render.sort} onChange={this.getSort}
                            onBlur={() => this.setSort(render.bannerId, render.sort)} />
                    )
                }
                // onChange={this.getSort}
            },
            {
                title: "跳转链接关联类型",
                dataIndex: "linkType",
                key: "linkType",
                render: (_, render) => {
                    return ["", "宠圈动态", "知识库","H5","官方推荐群"][render.linkType]
                }
            },
            {
                title: "动态编号",
                dataIndex: "linkNo",
                key: "linkNo",
            },
            {
                title: "图片",
                dataIndex: "bannerImages",
                key: "bannerImages",
                render: (text, render) => {
                    if (text) {
                        if (render.configCarouselShowType === 1) {
                            let arr = text.split('|')
                            return <TheImage preview={false} src={arr[1]} width={80} height={80} onClick={() => {
                                this.videoDialog(arr[0])
                            }} />
                        } else {
                            let arr = text.split(',')
                            return <Space>
                                {
                                    arr.map(v => {
                                        return <TheImage src={v} width={80} height={80} />
                                    })
                                }
                            </Space>
                        }
                    }
                }
            },
            {
                title: "备注",
                dataIndex: "remark",
                key: "remark",
            },
            {
                title: "修改时间",
                dataIndex: "updateTime",
                key: "updateTime",
                sorter: true,
            },
            {
                title: "修改人",
                dataIndex: "updateUserName",
                key: "updateUserName",
            },
            {
                title: "操作",
                fixed: "right",
                width: 200,
                render: (text, render) => {
                    return (
                        <div>
                            <TheButton haspermi={["petCircleUtil:resource:update"]} onClick={() => this.goEdit(render.bannerId)}>修改</TheButton>
                        </div>
                    );
                },
            },
            {
                title: "是否启用",
                fixed: "right",
                width: 200,
                render: (text, render) => {
                    return (
                        <div>
                            <TheSwitch haspermi={["petCircleUtil:resource:status"]} checked={render.status} onChange={(flag) => {
                                this.onChange(flag, render.sort, render.bannerId)
                            }} />
                        </div>
                    );
                },
            },
        ],
        bannerIds: [],
        dataSource: [],
        pageData: {
            // pageNo: 1,
            // pageSize: 10,
            current: 1,
            size: 10,
        },
        total: 0,
        newColumns: [],
        form_show: true,
        searchOption: [
            {
                field: 'bannerType',
                label: '资源位类型',
                placeholder: '全部',
                required: false,
                rules: [],
                type: 'Select',
                options: [{ value: 1, label: 'banner区' }, { value: 2, label: '内容首位资源位' }],
            },
            {
                field: 'bannerName',
                label: '资源位名称',
                placeholder: '请输入',
                required: false,
                rules: [],
                type: 'Input',
                defaultValue: ''
            },
            {
                field: 'status',
                label: '启用状态',
                placeholder: '全部',
                required: false,
                rules: [],
                type: 'Select',
                options: [{ value: 1, label: '启用' }, { value: 0, label: '关闭' }],
            },
        ],
        queryForm: { orders: [{ column: 'updateTime', asc: false }] }
    };

    componentDidMount() {
        this.onColumnsFilter(this.state.columns)
        let searchParams = store.getState().searchValue
        let { current, size, queryForm, pathName } = searchParams
        if (searchParams && current && pathName == 'resource') {
            this.setState({
                // queryForm,
                pageData: {
                    current,
                    size
                }
            }, () => {
                this.queryFormRef.onSetDefault({
                    ...queryForm
                })
                this.getData(queryForm)
            })
        } else {
            this.getData(this.state.queryForm)
        }
    };

    // 获取表格数据
    getData = async (values, sort) => {
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values, ...sort }
        }, async () => {
            let params = {
                ...this.state.pageData,
                ...this.state.queryForm
            }
            if (sort) {
                params = { ...params, ...sort }
            }
            console.log("params:", params);
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName: 'resource',
                    ...params
                }
            })
            let res = await apiBannerPage({
                ...params
            })
            if (res.code === 0 && res.data) {
                this.setState({
                    dataSource: res.data.records,
                    pageData: {
                        current: res.data.current,
                        size: res.data.size
                    },
                    total: res.data.total,
                })
            }
        })
    };

    // 新增
    goAdd = () => {
        this.props.history.push(`/petCircleUtil/resource/add/${0}`);
    };
    // 编辑
    goEdit = (id) => {
        this.props.history.push(`/petCircleUtil/resource/edit/${id}`);
    };
    //批量更改
    batchUpdateStatus = async (bannerIds, status) => {
        if (bannerIds.length <= 0) {
            React.$message({
                type: 'warning',
                content: `请选择资源位！`
            })
        } else {
            const res = await apiBannerDel({ bannerIds, status })
            if (res.code === 0) {
                this.setState({
                    selectedRowKeys: [],
                    pageData: {
                        current: 1,
                        size: 10
                    }
                }, () => {
                    this.getData(this.state.queryForm)
                })
            }
        }

    }
    //设置排序
    getSort = (number) => {
        this.setState({
            sort: number,
            changeFlag: true
        })
    }
    setSort = async (bannerId) => {
        //如果没有修改 就不调用
        if (!this.state.changeFlag) return
        this.setState({
            changeFlag: false
        })
        const sort = this.state.sort
        if (!sort || sort <= 0) {
            this.getData(this.state.queryForm)
            message.warning('请输入正确的排序');
            return
        }
        //排序数据传后台
        const res = await apiBannerEdit({ bannerId, sort })
        if (res.code === 0) {
            message.success("排序修改成功")
        } else {
            message.error(res.codeMessage)
        }
        this.getData(this.state.queryForm)
    }
    //启用/停用
    onChange = async (flag, sort, bannerId) => {
        if (sort <= 0 || !sort) {
            return message.error('请配置排序规则')
        }
        const status = flag ? 1 : 0
        const res = await apiBannerDel({ bannerIds: [bannerId], status })
        if (res.code === 0) {
            this.setState({
                pageData: {
                    current: 1,
                    size: 10
                }
            }, () => {
                this.getData(this.state.queryForm)
            })
        }
    }
    pageChange = (current, size) => {
        this.setState({
            pageData: {
                current,
                size
            }
        }, () => {
            this.getData()
        })
    };

    onReset() {
        this.setState({
            queryForm: { orders: [{ column: 'updateTime', asc: false }] }
        }, () => {
            this.pageChange(1, 10)
        })
    }

    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })
    }

    onFormSearch(values) {
        let orders = { orders: this.state.queryForm.orders }
        // if (values === {}) {
        //     values = undefined
        // }
        this.setState({
            pageData: { current: 1, size: 10 }
        }, () => {
            this.getData(values, orders)
        })
    }

    onSelectChange = (newSelectedRowKeys) => {
        this.setState({ selectedRowKeys: newSelectedRowKeys })
    }
    sorterFun = (pagination, filters, sorter) => {
        let sortType = sorter.order // 排序类型，正序/倒叙/不排序
        if (sortType) {
            this.getData(undefined, this.state.queryForm.orders = [{
                column: sorter.field,
                asc: sortType === 'ascend' ? true : false
            }]);
        } else {
            this.getData(undefined, this.state.queryForm.orders = { orders: [{ column: 'updateTime', asc: false }] })
        }
    }

    render() {
        const {
            columns,
            dataSource,
            pageData: { current, size },
            total,
            searchOption,
            form_show,
            newColumns,
            selectedRowKeys,
        } = this.state;
        const rowSelection = {
            selectedRowKeys, // 表格选择的Id
            preserveSelectedRowKeys: true,
            onChange: this.onSelectChange,
        };
        return (
            <div className={"p-layout-box commodity-content"}>
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                    onGetValues={(values) => this.onFormSearch(values)}
                    onReset={(values) => this.onReset(values)}
                >
                </TheQueryForm>
                <TheTableExtend
                    columns={columns}
                    onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                    onTableRefresh={() => this.getData()}
                    onColumnsFilter={(value) => this.onColumnsFilter(value)}
                >
                    <TheButton type="primary" haspermi={["petCircleUtil:resource:add"]} size="middle" onClick={this.goAdd}>
                        新建
                    </TheButton>
                    <TheButton type="primary" size="middle" haspermi={["petCircleUtil:resource:start"]} onClick={() => this.batchUpdateStatus(selectedRowKeys, 1)}>
                        批量启用
                    </TheButton>
                    <TheButton type="primary" size="middle" haspermi={["petCircleUtil:resource:stop"]} onClick={() => this.batchUpdateStatus(selectedRowKeys, 0)}>
                        批量停用
                    </TheButton>
                </TheTableExtend>
                <TheTable
                    scroll={{ x: "max-content", y: '61vh' }}
                    columns={newColumns}
                    dataSource={dataSource}
                    rowSelection={rowSelection}
                    rowKey={'bannerId'}
                    onChange={this.sorterFun}
                />
                <ThePagination
                    pageNo={current}
                    pageSize={size}
                    total={total}
                    pageChange={this.pageChange}
                />

            </div>
        );
    }
}

export default Resource;
